package com.zjuh.goodboy.util;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

public class IoUtil {
	
	private static final int BUF_LEN = 1024 * 8;
	
	public static void closeQuietly(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (IOException e) {
				// ignore
			}
		}
	}
	
	public static void copy(InputStream is, OutputStream os) throws IOException {
		byte[] buf = new byte[BUF_LEN];
		while (true) {
			int len = is.read(buf, 0, BUF_LEN);
			if (len < 0) {
				break;
			}
			os.write(buf, 0, len);
		}
	}
	
	public static void writeFileData(File file, byte[] data) throws IOException {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(file, "rw");
			raf.write(data);
		} finally {
			closeQuietly(raf);
		}
	}
	
	public static byte[] readFileData(File file) throws IOException {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(file, "r");
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buf = new byte[BUF_LEN];
			while (true) {
				int len = raf.read(buf, 0, BUF_LEN);
				if (len < 0) {
					break;
				}
				bos.write(buf, 0, len);
			}
			return bos.toByteArray();
		} finally {
			closeQuietly(raf);
		}
	}

}
